import os
from django.core.serializers import serialize
from django.shortcuts import render, redirect
from django.views import View
from newenergy import settings
from .models import *
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from utils.code import *
from reservation.models import Reservation
from django_redis import get_redis_connection
from users import service
from cars.models import CarEvaluate,Cars
from flashsale.models import *


#首页
def index(request):
    # email = request.session.get('email')
    # users = User.objects.get(email=email)
    user = request.session.get('user')
    if user:
        reservation_list = Reservation.objects.filter(user_id=user.id)
        number= len(reservation_list)
        return render(request, 'index.html',{'number':number})
    else:
        return render(request,'index.html')


#登入
class LoginView(View):
    def get(self, request):

        return render(request, 'templates/users/login.html')

    def post(self, request):
        name = request.POST.get('name')
        password = request.POST.get('password')
        print(name, password)
        user_list = User.objects.filter(name=name, password=password)
        print(user_list)
        if user_list:
            #将用户信息存入session对象中
            request.session['user'] = user_list[0]
            return HttpResponseRedirect('/')
        return HttpResponseRedirect('/login/')

#保存数字验证码
class LoadCodeView(View):
    def get(self,request):
        img, str = gene_code()
        #将验证码存入session
        request.session['session_code'] = str
        return HttpResponse(img, content_type='image/png')


#检查数字验证码
class CheckCodeView(View):
    def get(self,request):
        #获取GET请求过来的参数
        code = request.GET.get('code')

        #从session中获取存放的验证码
        session_code  = request.session.get('session_code')

        #判断是否相等
        flag = code == session_code
        return JsonResponse({'flag':flag})

#注册
class RgisterView(View):
    def get(self, request):

        return render(request, 'templates/users/register.html')

    def post(self, request):
        name = request.POST.get('name')
        email = request.POST.get('email')
        password = request.POST.get('password')

        # 插入数据库
        user = User.objects.create(name=name,email=email, password=password)
        print(user)
        # 判断是否注册成功
        if user:
            # 将用户信息存入session对象中
            request.session['user'] = user

            return HttpResponseRedirect("/")

        return HttpResponseRedirect("/register/")



# 获取邮箱

def email_code(request):
    email = request.GET.get('e')
    print(email)
    # 验证邮件地址格式
    ef = service.verify_email(email)
    if not ef:
        return JsonResponse({'message': '验证失败!'}, status=200)
    # pf:邮件是否发生成功
    pf = service.post_email(email)
    if not pf:
        return JsonResponse({'message': '发送失败!'}, status=200)
    print("发生验证码成功：", email)
    return JsonResponse({'message': 'Reservation deleted successfully!'}, status=200)



#t退出
class LogOutView(View):
    def get(self,request):
        del request.session['user']
        return HttpResponseRedirect("/")



#------------------------------------个人中心----------------------------
def personal(request):
    user = request.session.get('user')
    print(user.name,user.head)
    personal_list = User.objects.filter(id=user.id)
    users= User.objects.get(id=user.id)
    reservation_list = Reservation.objects.filter(user_id=user.id)
    number = len(reservation_list)
    return render(request, 'templates/users/personal.html', {'personal_list':personal_list, 'users':users, 'number':number})



#修改个人信息
class Modify_PersonalView(View):
    def get(self,request):
        user = request.session.get('user')
        users = User.objects.get(id=user.id)
        reservation_list = Reservation.objects.filter(user_id=user.id)
        number= len(reservation_list)
        return render(request, 'templates/users/modify_personal.html', {'users':users, 'number':number})

    def post(self, request):
        aname = request.POST.get('aname','未知')
        aphone = request.POST.get('aphone','未知')
        addr = request.POST.get('addr','未知')
        gender = request.POST.get('gender','保密')
        age = request.POST.get('age','保密')
        user = request.session.get('user')
        print(aname,aphone,addr)
        User.objects.filter(id=user.id).update(aname=aname, aphone=aphone, addr=addr,gender=gender,age=age)
        print("数据更新成功")
        user = request.session.get('user')
        users = User.objects.get(id=user.id)
        reservation_list = Reservation.objects.filter(user_id=user.id)
        number= len(reservation_list)
        return render(request, 'templates/users/modify_personal.html',{'users':users, 'number':number})


#修改密码
class Modify_PasswordlView(View):
    def get(self,request):
        user = request.session.get('user')
        email = User.objects.get(id=user.id)
        users = User.objects.get(id=user.id)
        reservation_list = Reservation.objects.filter(user_id=user.id)
        number= len(reservation_list)
        return render(request, 'templates/users/modify_password.html', {'email':email, 'users':users, 'number':number})

    def post(self, request):
        opassword = request.POST.get('opassword')
        spassword = request.POST.get('spassword')
        user = request.session.get('user')
        print(opassword,spassword)
        if opassword == spassword:
            User.objects.filter(id=user.id).update(password=spassword)
            print("修改成功")
            return HttpResponseRedirect('/logout/')
        else:
            return HttpResponseRedirect('/modify_password/')




#地址
class LoadAreaView(View):
    def get(self,request):
        # 获取请求参数
        pid = request.GET.get('pid',-1)
        pid = int(pid)

        # 根据父id查询区化信息
        area_list = Area.objects.filter(parentid=pid)

        # 进行序列化
        area_list_json = serialize('json',area_list)

        return JsonResponse({'area_list_json':area_list_json})


#检查用户名是否存在
class CheckUname(View):
    def get(self, request):
        # 获取用户参数
        name = request.GET.get('name', '')
        print(name)
        # 根据用户名查找数据库里的用户是否存在
        user_list = User.objects.filter(name=name)  # 如果用get(),没有查找到用户会直接报错，所以用filter()
        flag = False
        if user_list:
            flag = True
        return JsonResponse({'flag': flag})


#检查邮箱是否已经被绑定
class CheckEmail(View):
    def get(self, request):
        # 获取用户参数
        email = request.GET.get('e')
        print(f'检查邮箱{email}')
        # 根据用户名查找数据库里的用户是否存在
        user_list = User.objects.filter(email=email)  # 如果用get(),没有查找到用户会直接报错，所以用filter()
        flag = False
        if user_list:
            flag = True
        return JsonResponse({'flag': flag})


#检查用户名与密码是否匹配
class CheckUnames(View):
    def get(self, request):
        # 获取用户参数
        name = request.GET.get('name', '')
        password = request.GET.get('password', '')
        print(name,password)
        # 根据用户名查找数据库里的用户是否存在
        user_list = User.objects.filter(name=name,password=password)  # 如果用get(),没有查找到用户会直接报错，所以用filter()
        flag = False
        if user_list:
            flag = True
        return JsonResponse({'flag': flag})


#检查邮箱验证码是否有误
class CheckEcode(View):
    def get(self, request):
        EMAIL_KEY_TEMPL = 'email:verification:%s'
        vecode = request.GET.get('code','')
        email = request.GET.get('email','')
        print(vecode,email)
        cache = get_redis_connection(alias='verify_codes')
        cache_vecode = cache.get(EMAIL_KEY_TEMPL % email)
        flag = False
        if vecode != cache_vecode:
            flag = True

        return JsonResponse({'flag': flag})


#修改头像昵称
class Modify_HeadView(View):
    def get(self,request):
        user = request.session.get('user')
        users = User.objects.get(id=user.id)
        reservation_list = Reservation.objects.filter(user_id=user.id)
        number= len(reservation_list)
        return render(request, 'templates/users/modify_head.html', {'users':users, 'number':number})

    def post(self, request):
        uer = request.session.get('user')
        name = request.POST.get('name',uer.name)
        if request.FILES['image']:
            image = request.FILES['image']
            filename = image.name
            print(image,filename)
            # 指定一个目录来保存上传的图片

            upload_dir = settings.STATIC_URL

            # 确保目录存在
            if not os.path.exists(upload_dir):
                os.makedirs(upload_dir)

            full_path = os.path.join(upload_dir, filename)

            with open(full_path, 'wb+') as destination:
                for chunk in image.chunks():
                    destination.write(chunk)

            user = User.objects.get(id=uer.id)
            user.head = full_path
            user.name = name
            user.save()
            return HttpResponseRedirect('/modify_head/')
        else:
            print("没有文件")
            # 处理没有文件上传的情况
            return HttpResponseRedirect('/modify_head/')


# 活动详情
class ActivityView(View):
    def get(self,request):
        user = request.session.get('user')
        users = User.objects.get(id=user.id)
        active_list = Active.objects.filter(users_id=user.id)

        reservation_list = Reservation.objects.filter(user_id=user.id)
        number= len(reservation_list)
        return render(request, 'templates/users/activity.html', {'active_list':active_list, 'users':users, 'number':number})


#我的评论
class Myevaluate(View):
    def get(self,request):
        user = request.session.get('user')
        users = User.objects.get(id=user.id)
        reservation_list = Reservation.objects.filter(user_id=user.id)
        number= len(reservation_list)
        evaluate_list = CarEvaluate.objects.filter(user_id=user.id).select_related('Cars')
        return render(request,'templates/users/evaluate.html',{'evaluate_list':evaluate_list, 'users':users, 'number':number})
